package com.gct.interceptor;

import java.util.Calendar;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.gct.security.HttpURLSecurity;
import com.gct.util.Constants;

@Component
public class URLAuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String urlAuth = request.getParameter("d");
        if(null == urlAuth)
            return false;
        String[] params = urlAuth.split("&");
        if(params.length != 4)
            return false;
        String[] ts = params[0].split("=");
        if(ts.length != 2)
            return false;
        try {
            long curTime = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis();
            if(1800 <= curTime - Long.valueOf(ts[1]) || 0 > curTime - Long.valueOf(ts[1]))
                return false;
        } catch (NumberFormatException e) {
            return false;
        }

        String[] appVersion = params[1].split("=");
        if(appVersion.length != 2)
            return false;
        if(!Constants.appVersion.equals(appVersion[1]))
            return false;
        String[] sk = params[2].split("=");
        if(sk.length != 2)
            return false;
        if(!HttpURLSecurity.decrypt(sk[1]))
            return false;
        
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}
